<template>
  <div class="app-container travelApplicationDetails">
    <div class="apply-query">
      <el-row class="filter-query">
        <el-col><span>{{$t('cashFlowForm.queryCondition')}}</span></el-col>
      </el-row>
      <el-form :inline="true" ref="resetFrom" :model="listQuery" label-width="120px" style="padding: 0 20px">
        <el-row style="padding-bottom: 10px">
          <el-col :span="4">
            <div class="w20">
              <div class="labelName">{{$t('cashFlowForm.country')}}</div>
              <dict-select v-model="listQuery.country" code="country" :clearable="true" @change="setBg"></dict-select>
            </div>
          </el-col>
          <el-col :span="4">
            <div class="w20">
              <div class="labelName">Category</div>
              <el-select clearable
                         v-model="listQuery.bg" :clearable="true"
                         @change="changeBg" filterable
                         :placeholder="$t('cashFlowForm.placeholder.content')">
                <el-option v-for="item in bgList" :key="item" :label="item" :value="item"></el-option>
              </el-select>
            </div>
          </el-col>
          <el-col :span="4">
            <div class="w20">
              <div class="labelName">Account</div>
              <el-select clearable multiple collapse-tags
                         v-model="listQuery.bu" :clearable="true"
                         @change="changeBu" filterable
                         :placeholder="$t('cashFlowForm.placeholder.content')">
                <el-option v-for="item in buList" :key="item" :label="item" :value="item"></el-option>
              </el-select>
            </div>
          </el-col>
          <el-col :span="4">
            <div class="w20">
              <div class="labelName">{{$t('cashFlowForm.company')}}</div>
                <el-select clearable class="filter-item" v-model="listQuery.company"  :placeholder="$t('cashFlowForm.placeholder.content')">
                  <el-option v-for="item in companyList" :key="item.value" :label="item.label" :value="item.value"></el-option>
                </el-select>
            </div>
          </el-col>
          <el-col :span="4">
            <div class="w20">
              <div class="labelName">{{$t('cashFlowForm.timeCondition')}}</div>
              <el-date-picker style="width: 100%" v-model="listQuery.timeCondition" type="daterange" value-format="yyyy-MM-dd" range-separator="-" :start-placeholder="$t('cashFlowForm.placeholder.startDate')" :end-placeholder="$t('cashFlowForm.placeholder.endDate')"></el-date-picker>
            </div>
          </el-col>
          <el-col :span="4" style="margin-top: 32px">
            <el-button class="yt-btn yt-btn-ys" @click="handleFilter" :loading="loading">{{$t('cashFlowForm.search')}}</el-button>
            <div class="yt-btn btn" @click="reset">{{$t('cashFlowForm.reset')}}</div>
          </el-col>
        </el-row>
      </el-form>
    </div>

    <div class="data-list">
      <div class="list-contentg" style="position: relative;">
        <span style="border-bottom: 3px solid #6dcaa8; line-height: 46px; display: inline-block;">{{$t('cashFlowForm.moneyFlowStatement')}}</span>
        <div class="list-content-type">
          <div class="list-content-textType">{{$t('cashFlowForm.theViewMode')}}</div>
          <el-select class="filter-item" v-model="pattern"  :placeholder="$t('cashFlowForm.placeholder.content')">
            <el-option v-for="item in patternList" :key="item.value" :label="item.label" :value="item.value"></el-option>
          </el-select>
        </div>
      </div>
      <div style="padding: 20px 0 10px 0;">
        <el-row>
          <div v-if="!dynamicListFla && (pattern === '1' || pattern === '3')">
          <el-col :span="4">
            <div class="w20">
              <div class="labelName">{{$t('cashFlowForm.subprojects')}}</div>
              <el-select multiple clearable collapse-tags
                         class="filter-item"
                         v-model="subProject" :placeholder="$t('cashFlowForm.placeholder.content')">
                <el-option v-for="item in subProjectList" :key="item.value" :label="item.label" :value="item.value"></el-option>
              </el-select>
            </div>
          </el-col>
         </div>

        <div v-if="pattern === '3'">
         <el-col :span="4">
           <div class="w20">
             <div class="labelName">{{$t('cashFlowForm.projectName')}}</div>
             <el-select filterable clearable v-model="projectName" :placeholder="$t('cashFlowForm.placeholder.content')">
              <el-option v-for="item in thisProjectList" :key="item.value" :label="item.label" :value="item.value"></el-option>
             </el-select>
           </div>
         </el-col>
        </div>
          <el-col :span="4" style="margin-top: 32px;">
            <el-button v-if="!dynamicListFla && (pattern === '1' || pattern === '3')" class="yt-btn yt-btn-ys" @click="querySuper" :loading="loading">{{$t('cashFlowForm.search')}}</el-button>
            <div v-if="!dynamicListFla && (pattern === '1' || pattern === '3')" class="yt-btn btn" @click="reset1">{{$t('cashFlowForm.reset')}}</div>
            <el-button type="primary" class="yt-btn yt-btn-ys" @click="remit">{{$t('cashFlowForm.export')}}</el-button>
          </el-col>
        </el-row>
        <div v-if="dynamicListFla" style="margin-top: 10px;">
          <el-tag type="warning"><i class="el-icon-warning"></i>{{$t('cashFlowForm.selectTime')}}</el-tag>
        </div>
      </div>
      <div class="yt-dynamic-list" v-if="pattern === '1'">
        <div class="dynamic-title" :style="list.title1.length > 13 ? 'width: ' + Number(list.model1[0].length) * 120 + 'px;':'width: 100%;'">
          <template v-for="(i,index) in list.title1">
            <div v-if="index === 0" class="index" style="width: 170px">{{ i }}</div>
            <div v-else class="subset">{{ i }}</div>
          </template>
        </div>
        <div class="yt-dynamic-table" :style="list.title1.length >13 ?'width: ' + Number(list.model1[0].length) * 120 + 'px;':'width: 100%;'">
          <div v-for="(x,i) in list.model1" class="dynamic-box">
            <div :class="yIndex === 0 ? 'subset2' : 'subset'" v-for="(y,yIndex) in x">
              <div v-if="yIndex > 0 && y !== ''" v-format="'#,##0'" v-html="getInt(y)"></div>
              <div v-else>{{ y }}</div>
            </div>
          </div>
        </div>
      </div>
      <div class="yt-dynamic-list" v-if="pattern === '2'">
        <!--表頭區-->
        <div class="dynamic-title" :style="list.title2.length > 13? 'width: ' + Number(list.model2[0].length) * 120 + 'px;':'width: 100%;'">
          <template v-for="(i,index) in list.title2">
            <div v-if="index === 0" class="index" style="width: 50px">{{ i }}</div>
            <div v-else-if="index === 1" class="index" style="width: 70px">{{ i }}</div>
            <div v-else-if="index === 2" class="index" style="width: 150px">{{ i }}</div>
            <div v-else-if="index === 3" class="index" style="width: 170px">{{ i }}</div>
            <div v-else-if="index === 4" class="index" style="width: 100px">{{ i }}</div>
            <div v-else class="subset">{{ i }}</div>
          </template>
        </div>
        <!--內容區-->
        <div class="yt-dynamic-table" :style="list.title2.length > 13 ?'width: ' + Number(list.model2[0].length) * 120 + 'px;':'width: 100%;'">
          <div v-for="(x,i) in list.model2" class="dynamic-box">
            <span :class=" yIndex === 2 ? 'subset10' : (yIndex === 1 ? 'subset9' : (yIndex === 4 ? 'subset5' : (yIndex === 0 ? 'subset1' : yIndex === 3 ? 'subset2' : 'subset')))"
              v-for="(y,yIndex) in x" :style="x[2] === '' && x[3].indexOf('付款') === -1 && x[3].indexOf('支出') === -1 ? 'background:#b7dee8': x[3] === '' && list.model2[i-1][3].indexOf('付款') === -1 && list.model2[i-1][3].indexOf('支出') === -1 ? 'background:#92cddc' : x[3].indexOf('付款') !== -1 && x[2] === '' ? 'background:#f2dcdb' : x[3] === '' && list.model2[i-1][3].indexOf('付款') !== -1 ? 'background:#da9694' : x[2] === '' && x[3].indexOf('支出') !== -1 ? 'background:#f2dcdb' : x[3] === '' && list.model2[i-1][3].indexOf('支出') !== -1 ? 'background:#da9694' : ''">
              <span v-if="yIndex > 4 && y !== ''" v-format="'#,##0'" v-html="getInt(y)"></span>
              <span v-else>{{ y }}</span>
            </span>
          </div>
        </div>
      </div>
      <div class="yt-dynamic-list" v-if="pattern === '3'"> <!--:style="list.model3.length >9 ? 'width: ' + ((1055 + Number(list.model3[0].length - 7) * 105)) + 'px;':'width: 100%;'"-->
        <div class="dynamic-title" :style="'width: ' + ((1055 + Number(list.title3.length - 7) * 105)) + 'px;'">
          <template v-for="(i,index) in list.title3">
            <div v-if="index === 0" class="index" style="width: 50px">{{ i }}</div>
            <div v-else-if="index === 1" class="index" style="width: 100px">{{ i }}</div>
            <div v-else-if="index === 2" class="index" style="width: 115px">{{ i }}</div>
            <div v-else-if="index === 3" class="index" style="width: 400px">{{ i }}</div>
            <div v-else-if="index === 4" class="index" style="width: 70px">{{ i }}</div>
            <div v-else-if="index === 5" class="index" style="width: 150px">{{ i }}</div>
            <div v-else-if="index === 6" class="index" style="width: 170px">{{ i }}</div>
            <div v-else class="index" style="font-weight: bold;width: 104px">{{ i }}</div>
          </template>
        </div><!--:style="list.model3.length > 9 ? 'width: ' + ((1075 + Number(list.model3[0].length - 7) * 105)) + 'px;':'width: 100%;'"-->
        <div class="yt-dynamic-table" :style="'width: ' + ((1075 + Number(list.title3.length - 7) * 105)) + 'px;'">
          <div v-for="(x,i) in list.model3" class="dynamic-box">
            <span :class="yIndex === 0 ? 'subset1' //50px
            :  yIndex === 1 ? 'subset5' //100px
            : yIndex === 2 ? 'subset8' //115px
            : yIndex === 3 ? 'subset4' //400px
            :  yIndex === 4 ? 'subset9' //70px
            :  yIndex === 5 ? 'subset10' //150px
            : yIndex === 6 ? 'subset11' // 170px
            : 'subset7'"
            v-for="(y,yIndex) in x" :style="x.length - 1 === yIndex ? 'color:#ff9900' : ''">
              <span v-if="yIndex > 6 && y !== ''" v-format="'#,##0'" v-html="getInt(y)"></span>
              <span v-else>{{ y }}</span>
            </span>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
  import { getDeptByBuAndCountry } from '@/api/bu/index';
  import { countMoney } from '@/api/pmoReport/cashFlowForm';
  import YtGetTemplateSelect from '@/components/Yt-template/getTemplateSelect.vue';
  import formatter from '@/utils/formatter';

  export default {
    name: 'myManageDailyReport',
    components: {
      YtGetTemplateSelect,
      'dict-select': () => import('@/components/Dict/dictValueSelect')
    },
    data() {
      return {
        dynamicListFla: true,
        loading: false,
        pattern: '1',
        patternList: [{
          value: '1',
          label: this.$t('cashFlowForm.patternList.finance')
        }, {
          value: '2',
          label: this.$t('cashFlowForm.patternList.predict')
        }, {
          value: '3',
          label: 'Project'
        }],
        formatter,
        listAll: this.$store.getters.allDic,
        listMapAll: this.$store.getters.allMapDic,
        companyList: this.$store.getters.allDic.company,
        listQuery: {
          order: '', // 降序（desc）/升序（asc）
          orderBy: '', // 排序字段
          page: 1,
          limit: 10,
          company: '',
          startTime: '',
          endTime: '',
          bg: '',
          bu: [],
          timeCondition: []
        },

        total: 0,
        buList: [],
        bgList: [],
        list: {
          title1: [],
          title2: [],
          title3: [],
          model1: [],
          model2: [],
          model3: []
        },
        model1List: [],
        subProject: [],
        subProjectList: [{
          value: '1 預計入帳-未開發票',
          label: '預計入帳-未開發票'
        }, {
          value: '2 預計入帳',
          label: '預計入帳'
        }, {
          value: '3 預計入帳-逾期',
          label: '預計入帳-逾期'
        }, {
          value: '4 實際收入',
          label: '實際收入'
        }, {
          value: '1 預計付款-未收發票',
          label: '預計付款-未收發票'
        }, {
          value: '2 預計付款',
          label: '預計付款'
        }, {
          value: '3 預計付款-逾期',
          label: '預計付款-逾期'
        }, {
          value: '4 實際支出',
          label: '實際支出'
        }],
        projectName: '',
        thisProjectList: [],
        copyList: []
      };
    },
    mounted() {
      this.getQuery()
      this.getBg()
      if (this.listQuery.startTime.length !== 0) {
        this.getList();
      }
    },
    methods: {
      reset1() {
        this.subProject = []
        this.projectName = ''
        this.list = JSON.parse(JSON.stringify(this.copyList))
      },
      superLoad() {
        this.copyList = JSON.parse(JSON.stringify(this.list))
        const projects = this.list.model3
        projects.forEach(item => {
          const param = {};
          param.value = item[2];
          param.label = item[3];
          this.thisProjectList.push(param)
        });
        const res = new Map();
        this.thisProjectList = this.thisProjectList.filter(item => !res.has(item.value) && res.set(item.value, 1));
      },
      querySuper() {
        const subList = []
        if (this.subProject.length === 0) {
          this.list = JSON.parse(JSON.stringify(this.copyList))
        } else {
          this.subProject.forEach(item => {
            subList.push(item.substring(1).trim())
          })
        }
        switch (this.pattern) {
          // eslint-disable-next-line no-case-declarations
          case '1':
            const res1 = []
            subList.forEach(sub => {
              this.copyList.model1.forEach(item => {
                if (sub === item[0]) {
                  res1.push(item)
                }
              });
            });
            this.list.model1 = res1
            return '';
          // eslint-disable-next-line no-case-declarations
          case '3':
            if (this.projectName === '' && this.subProject === '') {
              this.list = JSON.parse(JSON.stringify(this.copyList))
            } else {
              const res3 = [];
              if (this.projectName !== '' && this.subProject.length > 0) {
                this.subProject.forEach(sub => {
                  this.copyList.model3.forEach(item => {
                    if (sub === item[6] && this.projectName === item[2]) {
                      res3.push(item)
                    }
                  })
                })
              } else if (this.subProject.length > 0) {
                this.subProject.forEach(sub => {
                  this.copyList.model3.forEach(item => {
                    if (sub === item[6]) {
                      res3.push(item)
                    }
                  });
                });
              } else if (this.projectName !== '') {
                this.copyList.model3.forEach(item => {
                  if (this.projectName === item[2]) {
                    res3.push(item)
                  }
                });
              }
              this.list.model3 = res3
            }
            return '';
        }
      },
      getQuery() {
        const cashFlowFormListQuery = window.sessionStorage.getItem('cashFlowFormListQuery');
        if (cashFlowFormListQuery) {
          this.listQuery = JSON.parse(cashFlowFormListQuery);
        }
      },
      setBg(country) {
        this.listQuery.bu = []
        this.listQuery.bg = ''
        if (country) {
          const bgSet = []
          if (this.listQuery.bg !== '') {
            bgSet.push(this.listQuery.bg)
          }
          const param = {}
          param.country = country
          param.bg = bgSet
          param.bu = this.listQuery.bu
          getDeptByBuAndCountry(param).then(res => {
            this.bgList = res.data.bgList
            this.buList = res.data.buList
          })
        } else {
          this.getBg()
        }
      },
      getBg() {
        const param = {}
        getDeptByBuAndCountry(param).then(res => {
          if (res) {
            this.buList = res.data.buList
            this.bgList = res.data.bgList
          }
        })
      },
      changeBg(row) {
        this.listQuery.bu = []
        const bgSet = []
        if (row !== '') {
          bgSet.push(row)
        }
        const param = {}
        param.country = this.listQuery.country
        param.bg = bgSet
        param.bu = []
        getDeptByBuAndCountry(param).then(res => {
          this.buList = res.data.buList
        })
      },
      changeBu(row) {
        if (row.length === 0) {
          this.listQuery.bu = []
        }
      },
      remit() {
        if (this.listQuery.timeCondition == null) {
          this.listQuery.startTime = '';
          this.listQuery.endTime = '';
          this.$message.error(this.$t('cashFlowForm.message.message1'))
          return false
        }
        if (this.listQuery.timeCondition.length === 0) {
          this.listQuery.startTime = '';
          this.listQuery.endTime = '';
          this.$message.error(this.$t('cashFlowForm.message.message1'))
          return false
        }
        this.listQuery.startTime = this.listQuery.timeCondition[0];
        this.listQuery.endTime = this.listQuery.timeCondition[1];

        const a = document.createElement('a');
        const href = '/api/admin/excel/exportCountMoney?startTime=' + this.listQuery.startTime + '&endTime=' + this.listQuery.endTime + '&bg=' + this.listQuery.bg + '&bu=' + this.listQuery.bu + '&company=' + this.listQuery.company + '&viewModel=' + this.pattern + '&userId=' + this.$store.getters.info.id;
        a.download = Date.now();
        a.href = href;
        a.click();
      },
      reset() {
        this.listQuery = {
          order: '', // 降序（desc）/升序（asc）
          orderBy: '', // 排序字段
          page: 1,
          limit: 10,
          company: '',
          startTime: '',
          endTime: '',
          bg: '',
          bu: [],
          timeCondition: []
        };
      },
      handleFilter() {
        this.getList();
      },
      handleSizeChange(val) {
        this.listQuery.limit = val;
        this.getList();
      },
      getInt(val) {
        if (val && val !== '') {
          try {
            return parseInt(val);
          } catch (e) {
            return val;
          }
        } else {
          return '';
        }
      },
      handleCurrentChange(val) {
        this.listQuery.page = val;
        this.getList();
      },
      handlePreserve(row) {
        this.$router.push({ path: '/dailyManagement/myDailyManageLook', query: { id: row.id } })
      },
      async getList() {
        if (this.listQuery.timeCondition == null) {
          this.listQuery.startTime = '';
          this.listQuery.endTime = '';
          this.$message.error(this.$t('cashFlowForm.message.message1'))
          return false
        }
        if (this.listQuery.timeCondition.length === 0) {
          this.listQuery.startTime = '';
          this.listQuery.endTime = '';
          this.$message.error(this.$t('cashFlowForm.message.message1'))
          return false
        }
        this.loading = true
        if (this.listQuery.timeCondition && Array.isArray(this.listQuery.timeCondition) && this.listQuery.timeCondition.length === 2) {
          this.listQuery.startTime = this.listQuery.timeCondition[0];
          this.listQuery.endTime = this.listQuery.timeCondition[1];
        }
        await countMoney(this.listQuery).then(res => {
          this.list = res.data
          this.dynamicListFla = false
          this.superLoad();
        });
        this.loading = false
      }
    },
    beforeDestroy() {
      window.sessionStorage.setItem('cashFlowFormListQuery', JSON.stringify(this.listQuery))
    }
  };
</script>
<style lang="scss" scoped>
  .yt-dynamic-list{
    border-right: 1px solid #ebeef5;
    overflow-x: auto;
  }
  .dynamic-title{
    display: flex;
    flex-direction: row;
    flex-wrap: wrap;
    width: 100%;
    .index{
      background-color: #f1f4f3;
      padding: 10px;
      text-align: center;
      font-size: 12px;
      font-weight: bold;
      color: #212121;
    }
    .subset{
      flex: 1;
      background-color: #f1f4f3;
      color: #212121;
      padding: 10px;
      font-size: 12px;
      word-break : break-all;
      overflow:hidden;
      text-align: center;
      font-weight: bold
    }
  }
  .yt-dynamic-table {
    max-height: 600px;
    min-height: 30px;
    overflow: hidden auto;
    .dynamic-box{
      display: flex;
      flex-direction: row;
      flex-wrap: wrap;
      width: 100%;
      .subset{
        flex: 1;
        color: #212121;
        padding: 10px;
        font-size: 12px;
        color: #606266;
        border-left: 1px solid #ebeef5;
        border-bottom: 1px solid #ebeef5;
        word-break : break-all;
        overflow:hidden;
        text-align: center;
        /*min-width: 130px;*/
      }
      .subset1{
        width: 50px;
        color: #212121;
        padding: 10px;
        font-size: 12px;
        color: #606266;
        border-left: 1px solid #ebeef5;
        border-bottom: 1px solid #ebeef5;
        word-break : break-all;
        overflow:hidden;
        text-align: center;
      }
      .subset2{
        width: 170px;
        color: #212121;
        padding: 10px;
        font-size: 12px;
        color: #606266;
        border-left: 1px solid #ebeef5;
        border-bottom: 1px solid #ebeef5;
        word-break : break-all;
        overflow:hidden;
        text-align: center;
      }
      .subset3{
        width: 136px;
        color: #212121;
        padding: 10px;
        font-size: 12px;
        color: #606266;
        border-left: 1px solid #ebeef5;
        border-bottom: 1px solid #ebeef5;
        word-break : break-all;
        overflow:hidden;
        text-align: center;
      }
      .subset4{
        width: 400px;
        color: #212121;
        padding: 10px;
        font-size: 12px;
        color: #606266;
        border-left: 1px solid #ebeef5;
        border-bottom: 1px solid #ebeef5;
        word-break : break-all;
        overflow:hidden;
        text-align: center;
      }
      .subset5{
        width: 100px;
        color: #212121;
        padding: 10px;
        font-size: 12px;
        color: #606266;
        border-left: 1px solid #ebeef5;
        border-bottom: 1px solid #ebeef5;
        word-break : break-all;
        overflow:hidden;
        text-align: center;
      }
      .subset6{
        width: 110px;
        color: #212121;
        padding: 10px;
        font-size: 12px;
        color: #606266;
        border-left: 1px solid #ebeef5;
        border-bottom: 1px solid #ebeef5;
        word-break : break-all;
        overflow:hidden;
        text-align: center;
      }
      .subset7{
        width: 104px;
        color: #212121;
        padding: 10px;
        font-size: 12px;
        color: #606266;
        border-left: 1px solid #ebeef5;
        border-bottom: 1px solid #ebeef5;
        word-break : break-all;
        overflow:hidden;
        text-align: center;
      }
      .subset8{
        width: 115px;
        color: #212121;
        padding: 10px;
        font-size: 12px;
        color: #606266;
        border-left: 1px solid #ebeef5;
        border-bottom: 1px solid #ebeef5;
        word-break : break-all;
        overflow:hidden;
        text-align: center;
      }
      .subset9{
        width: 70px;
        color: #212121;
        padding: 10px;
        font-size: 12px;
        color: #606266;
        border-left: 1px solid #ebeef5;
        border-bottom: 1px solid #ebeef5;
        word-break : break-all;
        overflow:hidden;
        text-align: center;
      }
      .subset10{
        width: 150px;
        color: #212121;
        padding: 10px;
        font-size: 12px;
        color: #606266;
        border-left: 1px solid #ebeef5;
        border-bottom: 1px solid #ebeef5;
        word-break : break-all;
        overflow:hidden;
        text-align: center;
      }
      .subset11{
        width: 170px;
        color: #212121;
        padding: 10px;
        font-size: 12px;
        color: #606266;
        border-left: 1px solid #ebeef5;
        border-bottom: 1px solid #ebeef5;
        word-break : break-all;
        overflow:hidden;
        text-align: center;
      }
      span{
        justify-content: center;
        align-items: center;
        display: flex;
      }
    }
  }
  .list-contentg{
    color: #6dcaa8;
    height: 50px;
    line-height: 50px;
    border-bottom: solid 1px #d3d3d3;
    font-size: 14px;
    padding-left: 20px;
    margin: 0 -20px;
  }
  .list-content-type{
    width: 200px;
    position: absolute;
    top: 0;
    right: 20px;
    .list-content-textType{
      position: absolute;
      left: -65px;
      font-size: 12px;
      color: #606266;
    }
  }
</style>
